package com.fenghongzhang.day012;

import android.content.ContentResolver;
import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.os.Handler;
import android.os.Message;
import android.provider.Telephony;


//内容观察者
public class MyObserver extends ContentObserver {
    private Context context;
    private Handler handler;
    public MyObserver(Handler handler,Context context) {
        super(handler);
        this.handler = handler;
        this.context =context;
    }
    /**
     * 一但监视内容有变化,会自动调用onChange方法
     * @param selfChange
     */
    @Override
    public void onChange(boolean selfChange) {
        super.onChange(selfChange);
        //监视短信数据
        ContentResolver contentResolver = context.getContentResolver();
        Cursor query = contentResolver.query(Telephony.Sms.CONTENT_URI, null, null, null, null);
        if(query != null){
            query.moveToFirst();
            String body = query.getString(query.getColumnIndex(Telephony.Sms.BODY));

            Message obtain = Message.obtain();
            obtain.obj = body;
            handler.sendMessage(obtain);

            query.close();
        }

    }
}
